package com.yuelao.yuelao_backend.controller;

import com.yuelao.yuelao_backend.common.ApiResponse;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.DailyActionStatsDTO;
import com.yuelao.yuelao_backend.dto.UserDTO;
import com.yuelao.yuelao_backend.dto.response.LikeUserResponse;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.entity.UserFollow;
import com.yuelao.yuelao_backend.entity.UserMatch;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuelao.yuelao_backend.service.*;
import com.yuelao.yuelao_backend.util.UserContextUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 用户关系Controller
 * 处理用户喜欢、配对、关系状态等核心功能
 */
@RestController
@RequestMapping("/relation")
@Slf4j
@RequiredArgsConstructor
public class RelationController {

    private final UserLikeService userLikeService;
    private final UserMatchService userMatchService;
    private final UserService userService;
    private final DailyActionRecordService dailyActionRecordService;
    private final UserFollowService userFollowService;

    /**
     * 喜欢用户
     * POST /relation/like
     * @param request 喜欢请求
     * @return 是否配对成功
     */
    @PostMapping("/like")
    @Transactional
    public ApiResponse<LikeUserResponse> likeUser(@Valid @RequestBody LikeUserRequest request) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        // 获取用户VIP状态
        User user = userService.getById(userId);
        boolean isVip = user.getIsVip() != null && user.getIsVip();
        
        boolean isSuper = request.getIsSuper() != null && request.getIsSuper();
        
        // 检查今日限制
        if (isSuper) {
            if (!dailyActionRecordService.canSuperLikeToday(userId, isVip)) {
                throw new BizException(ErrorCode.OPERATION_ERROR, 
                    isVip ? "今日超级喜欢次数已用完" : "普通用户无法使用超级喜欢，请升级VIP");
            }
        } else {
            if (!dailyActionRecordService.canLikeToday(userId, isVip)) {
                throw new BizException(ErrorCode.OPERATION_ERROR, "今日喜欢次数已用完");
            }
        }
        
        boolean success;
        
        if (isSuper) {
            success = userLikeService.superLikeUser(userId, request.getUserId());
        } else {
            success = userLikeService.likeUser(userId, request.getUserId());
        }
        
        // 记录今日操作
        if (success) {
            dailyActionRecordService.incrementLikeCount(userId, isSuper);
        }
        
        // 检查是否配对成功
        boolean isMatch = userMatchService.isMatched(userId, request.getUserId());
        
        // 如果配对成功，记录今日新配对
        if (isMatch) {
            dailyActionRecordService.incrementMatchCount(userId);
        }
        
        LikeUserResponse response = LikeUserResponse.builder()
                .isMatch(isMatch)
                .reward(isMatch ? 20 : 0)
                .build();
        
        return ApiResponse.ok(response,isMatch ? "配对成功！" : null);
    }

    /**
     * 不喜欢用户
     * POST /relation/dislike
     * @param request 不喜欢请求
     * @return 操作结果
     */
    @PostMapping("/dislike")
    public ApiResponse<Boolean> dislikeUser(@Valid @RequestBody LikeUserRequest request) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        // 获取用户VIP状态
        User user = userService.getById(userId);
        boolean isVip = user.getIsVip() != null && user.getIsVip();
        
        // 检查今日限制（不喜欢也消耗喜欢次数）
        if (!dailyActionRecordService.canLikeToday(userId, isVip)) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "今日喜欢次数已用完");
        }
        
        // 只记录操作次数，不记录到like表
        dailyActionRecordService.incrementLikeCount(userId, false);
        
        return ApiResponse.ok(true);
    }

    /**
     * 获取我喜欢的人列表
     * GET /relation/my-likers
     * @param page 页码
     * @param size 每页数量
     * @return 用户列表
     */
    @GetMapping("/my-likers")
    public ApiResponse<Map<String, Object>> getMyLikers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        // 获取我喜欢的人ID列表
        List<Long> likedUserIds = userLikeService.getMyLikes(userId, page, size);
        
        // 转换为UserDTO
        List<UserDTO> userList = likedUserIds.stream()
                .map(userService::getUserInfo)
                .collect(Collectors.toList());
        
        // 统计数据
        long total = userLikeService.countMyLikes(userId);
        long mutualCount = userLikeService.countMutualLikes(userId);
        long superMatchCount = userLikeService.countSuperMatches(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", userList);
        result.put("total", total);
        result.put("mutual_count", mutualCount);
        result.put("super_match_count", superMatchCount);
        
        return ApiResponse.ok(result);
    }

    /**
     * 获取喜欢我的人列表
     * GET /relation/who-likes-me
     * @param page 页码
     * @param size 每页数量
     * @return 用户列表
     */
    @GetMapping("/who-likes-me")
    public ApiResponse<Map<String, Object>> getWhoLikesMe(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = UserContextUtil.getCurrentUserId();
        // 检查用户是否VIP
        UserDTO currentUser = userService.getCurrentUser(userId);
        if (currentUser.getIsVip() == null || !currentUser.getIsVip()) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "该功能仅限VIP用户使用");
        }
        
        // 获取喜欢我的人ID列表
        List<Long> likerIds = userLikeService.getWhoLikesMe(userId, page, size);
        
        // 转换为UserDTO
        List<UserDTO> userList = likerIds.stream()
                .map(userService::getUserInfo)
                .collect(Collectors.toList());
        
        // 统计数据
        long total = userLikeService.countWhoLikesMe(userId);
        long mutualCount = userLikeService.countMutualLikes(userId);
        long superMatchCount = userLikeService.countSuperMatches(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", userList);
        result.put("total", total);
        result.put("mutual_count", mutualCount);
        result.put("super_match_count", superMatchCount);
        
        return ApiResponse.ok(result);
    }

    /**
     * 获取配对列表
     * GET /relation/my-matches
     * @param page 页码
     * @param size 每页数量
     * @return 配对列表
     */
    @GetMapping("/my-matches")
    public ApiResponse<Map<String, Object>> getMyMatches(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        List<UserMatch> matches = userMatchService.getUserMatches(userId);
        
        // 分页
        int start = (page - 1) * size;
        int end = Math.min(start + size, matches.size());
        List<UserMatch> pagedMatches = matches.subList(start, Math.min(end, matches.size()));
        
        // 转换为UserDTO
        List<UserDTO> matchList = pagedMatches.stream()
                .map(match -> userService.getUserInfo(match.getMatchedUserId()))
                .collect(Collectors.toList());
        
        // 统计数据
        long totalMatches = userMatchService.countTotalMatches(userId);
        long superMatchCount = userMatchService.countSuperMatches(userId);
        long todayNewMatch = userMatchService.getTodayNewMatchCount(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", matchList);
        result.put("total", totalMatches);
        result.put("super_match_count", superMatchCount);
        result.put("today_new_match", todayNewMatch);
        
        return ApiResponse.ok(result);
    }

    /**
     * 获取用户关系状态
     * GET /relation/status/{userId}
     * @param targetUserId 目标用户ID
     * @return 关系状态
     */
    @GetMapping("/status/{userId}")
    public ApiResponse<Map<String, Object>> getRelationStatus(@PathVariable("userId") Long targetUserId) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        if (targetUserId == null || targetUserId <= 0) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "目标用户ID无效");
        }
        
        // 检查是否喜欢对方
        boolean iLike = userLikeService.hasLiked(userId, targetUserId);
        
        // 检查对方是否喜欢我
        boolean likeMe = userLikeService.hasLiked(targetUserId, userId);
        
        // 检查是否配对
        boolean isMatched = userMatchService.isMatched(userId, targetUserId);
        
        // 检查是否关注对方
        boolean iFollow = userFollowService.isFollowing(userId, targetUserId);
        
        // 检查对方是否关注我
        boolean followMe = userFollowService.isFollowing(targetUserId, userId);
        
        // 确定关系状态（优先级：匹配 > 互相关注 > 我关注 > 对方关注我 > 互相喜欢 > 我喜欢 > 对方喜欢我 > 陌生人）
        String status;
        if (isMatched) {
            status = "mutual_like";
        } else if (iFollow && followMe) {
            status = "mutual_follow";
        } else if (iFollow) {
            status = "i_follow";
        } else if (followMe) {
            status = "follow_me";
        } else if (iLike && likeMe) {
            status = "mutual_like";
        } else if (iLike) {
            status = "i_like";
        } else if (likeMe) {
            status = "like_me";
        } else {
            status = "stranger";
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("status", status);
        result.put("can_like", !iLike);
        result.put("can_follow", !iFollow); // 基于实际关注状态判断
        result.put("can_chat", isMatched); // 只有配对后才能聊天
        
        return ApiResponse.ok(result);
    }

    /**
     * 获取今日操作统计
     * GET /relation/today-stats
     * @return 今日统计
     */
    @GetMapping("/today-stats")
    public ApiResponse<DailyActionStatsDTO> getTodayStats() {
        Long userId = UserContextUtil.getCurrentUserId();
        
        // 获取用户VIP状态
        User user = userService.getById(userId);
        boolean isVip = user.getIsVip() != null && user.getIsVip();
        
        // 获取今日统计
        DailyActionStatsDTO result = dailyActionRecordService.getTodayStats(userId, isVip);
        
        return ApiResponse.ok(result);
    }

    /**
     * 关注用户（路由别名）
     * POST /relation/follow
     * @param request 关注请求
     * @return 是否成功
     */
    @PostMapping("/follow")
    public ApiResponse<Boolean> followUser(@Valid @RequestBody FollowUserRequest request) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        // 检查用户VIP状态
        User user = userService.getById(userId);
        boolean isVip = user != null && user.getIsVip() != null && user.getIsVip();
        
        // 检查今日关注限制
        if (!dailyActionRecordService.canFollowToday(userId, isVip)) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "今日关注次数已用完");
        }
        
        boolean result = userFollowService.followUser(userId, request.getUserId());
        
        // 记录今日操作
        if (result) {
            dailyActionRecordService.incrementFollowCount(userId);
        }
        
        return ApiResponse.ok(result);
    }

    /**
     * 获取我关注的人列表
     * GET /relation/my-follows
     * @param page 页码
     * @param size 每页数量
     * @return 关注列表
     */
    @GetMapping("/my-follows")
    public ApiResponse<List<UserDTO>> getMyFollows(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = UserContextUtil.getCurrentUserId();
        List<UserDTO> followList = userFollowService.getFollowingList(userId, page, size);
        return ApiResponse.ok(followList);
    }

    /**
     * 获取关注我的列表
     * GET /relation/my-followers
     * @param page 页码
     * @param size 每页数量
     * @return 粉丝列表
     */
    @GetMapping("/my-followers")
    public ApiResponse<Map<String, Object>> getMyFollowers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = UserContextUtil.getCurrentUserId();
        List<UserDTO> followerList = userFollowService.getFollowerList(userId, page, size);
        
        // 统计总数
        LambdaQueryWrapper<UserFollow> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(UserFollow::getFollowedUserId, userId);
        long total = userFollowService.count(countWrapper);
        
        // 统计互相关注数量（总数）：获取所有关注我的用户ID，然后检查我是否也关注了这些用户
        LambdaQueryWrapper<UserFollow> followerIdsWrapper = new LambdaQueryWrapper<>();
        followerIdsWrapper.eq(UserFollow::getFollowedUserId, userId)
                .select(UserFollow::getUserId);
        List<UserFollow> allFollowers = userFollowService.list(followerIdsWrapper);
        List<Long> followerIds = allFollowers.stream()
                .map(UserFollow::getUserId)
                .collect(Collectors.toList());
        
        // 统计互相关注：检查我是否也关注了这些用户
        long mutualFollowCount = 0;
        if (!followerIds.isEmpty()) {
            LambdaQueryWrapper<UserFollow> mutualCountWrapper = new LambdaQueryWrapper<>();
            mutualCountWrapper.eq(UserFollow::getUserId, userId)
                    .in(UserFollow::getFollowedUserId, followerIds);
            mutualFollowCount = userFollowService.count(mutualCountWrapper);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", followerList);
        result.put("total", total);
        result.put("mutual_count", mutualFollowCount);
        
        return ApiResponse.ok(result);
    }

    /**
     * 取消关注用户
     * DELETE /relation/unfollow
     * @param request 取消关注请求
     * @return 是否成功
     */
    @DeleteMapping("/unfollow")
    public ApiResponse<Boolean> unfollowUser(@Valid @RequestBody FollowUserRequest request) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        if (request.getUserId() == null || request.getUserId() <= 0) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "用户ID无效");
        }
        
        boolean result = userFollowService.unfollowUser(userId, request.getUserId());
        
        return ApiResponse.ok(result, result ? "取消关注成功" : "取消关注失败");
    }

    /**
     * 喜欢用户请求DTO
     */
    @lombok.Data
    public static class LikeUserRequest {
        @jakarta.validation.constraints.NotNull(message = "用户ID不能为空")
        private Long userId;
        
        private Boolean isSuper; // 是否超级喜欢
    }

    /**
     * 关注用户请求DTO
     */
    @lombok.Data
    public static class FollowUserRequest {
        @jakarta.validation.constraints.NotNull(message = "用户ID不能为空")
        private Long userId;
    }
}

